<template>
  <div v-loading="loading" element-loading-text="正在上传">
    <div>
      <el-upload
        class="upload-demo"
        drag
        :headers="{Authorization:'Bearer ' + getToken}"
        :action="baseurl+'/system/student/import'"
        accept=".xlsx"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        multiple
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip" style="text-align: center">
          仅允许导入xlsx格式文件。
          <span @click="loadModel">下载模板</span>
        </div>
      </el-upload>
    </div>
    <div />
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'Index',
  data() {
    return {
      loading: false,
      timer: '',
      baseurl: process.env.VUE_APP_BASE_API,
      getToken: getToken()
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  methods: {
    beforeUpload() {
      this.loading = true
    },
    uploadSuccess(response, file) {
      this.loading = false
      if (response.code === 200) {
        this.$message({
          type: 'success',
          message: '成功导入学生信息'
        })
        this.$emit('success')
      } else {
        this.$alert(response.msg, '错误提示', {
          confirmButtonText: '确定',
          customClass: 'custom-message'
        })
      }
    },
    uploadError(response, file) {
      this.$message({
        type: 'error',
        message: '上传文件失败'
      })
      this.loading = false
    },
    loadModel() {
      const a = document.createElement('a')
      a.href = './file/学生导入模板.xlsx'
      a.download = '学生导入模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
      this.$message({
        type: 'success',
        message: '正在下载模板！请注意查收'
      })
    }
  }
}
</script>

<style scoped lang="scss">
span{
  color: #00afff;
  cursor: pointer;
}
</style>
